﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YasharEl.Infrastructure.Diagnostics.Logging;
using YasharEl.Infrastructure.ObjectFactory;

namespace YasharEl.Infrastructure.ExceptionHandling.Logging
{
    public class LoggingExceptionHandler : IExceptionHandler
    {
        public LoggingExceptionHandler()
        {

        }

        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            Type declaringType = exception.TargetSite.DeclaringType;

            if (declaringType.IsGenericTypeDefinition)
            {
                // When declaring type is open generic type, we can't CretaeInstance of it.
                // and we use object instead of open generic type.
                declaringType = typeof(object);
            }

            Type loggerType =
                typeof(ILogger<>)
                    .MakeGenericType(
                        new Type[] 
                        { 
                            declaringType
                        }
                    );

            // Resolve logger by dynamic generic created logger type.
            ILogger logger = (ILogger)DependencyContainer.Resolve(loggerType);

            logger.Error("Error with instance id '{0}' occurred due to '{1}'.", handlingInstanceId, exception);

            return exception;
        }
    }
}
